package stmo.栈;

public class ReversePolishNotationTest {

    /**
     *  逆波兰表达式问题
     */


    public static void main(String[] args) {

        String[] notation = {"3","17","15","-","*","18","6","/","+"};
        int result = caculate(notation);
        System.out.println("逆波兰表达式的结果为："+result);
    }


    private static int caculate(String[] notation) {

        //定义一个栈，用来存储操作数
        Stack<Integer> stack = new Stack();

        //从左往右遍历逆波兰表达式，得到每一个元素
        for (int i = 0;i < notation.length;i++) {
            String curr = notation[i];
            //判断当前元素是运算符还是操作数
            Integer o1;
            Integer o2;
            Integer result;
            switch (curr) {
                //是运算符，从栈中弹出两个操作数，完成运算，运算完的结果再压入栈中
                case "+":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    result = o2 + o1;
                    stack.push(result);
                    break;
                case "-":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    result = o2 - o1;
                    stack.push(result);
                    break;
                case "*":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    result = o2 * o1;
                    stack.push(result);
                    break;
                case "/":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    result = o2 / o1;
                    stack.push(result);
                    break;
                //操作数，把该操作数放入栈中
                default:
                    stack.push(Integer.parseInt(curr));
                    break;
            }
        }

        //得到栈中最后一个元素，就是逆波兰表达式的结果
        Integer result = stack.pop();

        return result;
    }
}
